package com.kbtd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kbtd.dto.Result;
import com.kbtd.dto.UserDTO;
import com.kbtd.entity.Follow;
import com.kbtd.entity.User;
import com.kbtd.mapper.FollowMapper;
import com.kbtd.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kbtd.service.IUserService;
import com.kbtd.utils.UserHolder;
import com.kbtd.utils.redis.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.kbtd.constant.RedisConstants.FOLLOW_KEY_PREFIX;

/**
 * 关注服务实现类
 *
 * @author wp
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    //用户是否关注
    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisUtils.createKey(FOLLOW_KEY_PREFIX, userId.toString());
        //判断是否关注
        Boolean isFollow = stringRedisTemplate.opsForSet().isMember(key, followUserId.toString());
        return Result.ok(Boolean.TRUE.equals(isFollow));
    }

    //关注/取关
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = RedisUtils.createKey(FOLLOW_KEY_PREFIX, userId.toString());
        //判断是否关注
        if (isFollow.equals(isFollow(followUserId).getData())) {
            String errMsg = isFollow ? "用户已关注！" : "用户未关注！";
            return Result.fail(errMsg);
        }
        if (isFollow) {
            //关注，则将信息保存到数据库
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean succeed = save(follow);
            //则将数据也写入Redis
            if (succeed) {
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            //取关，则将数据从数据库中移除
            boolean succeed = remove(query().eq("user_id", userId)
                    .eq("follow_user_id",followUserId));
            //则将数据也从Redis中移除
            if (succeed){
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    //共同关注
    @Override
    public Result followCommons(Long anotherUserId) {
        Long userId = UserHolder.getUser().getId();
        String meKey = RedisUtils.createKey(FOLLOW_KEY_PREFIX, userId.toString());
        String anotherKey = RedisUtils.createKey(FOLLOW_KEY_PREFIX, anotherUserId.toString());
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(meKey, anotherKey);
        if (ObjectUtils.isEmpty(intersect)) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream()
                .map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOs = users.stream()
                .map(user -> {
                    UserDTO userDTO = new UserDTO();
                    BeanUtils.copyProperties(user, userDTO);
                    return userDTO;
                })
                .collect(Collectors.toList());
        return Result.ok(userDTOs);
    }
}
